package com.baayso.bms2.config.spring.web;

import javax.servlet.Filter;
import javax.servlet.ServletRegistration.Dynamic;

import org.springframework.core.annotation.Order;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.baayso.bms2.config.spring.AppConfig;

/**
 * Spring DispatcherServlet的配置，其它servlet和监听器等需要额外声明，用@Order注解设定启动顺序
 * 
 * @author ChenFangjie(2015年9月19日 下午9:03:48)
 * 
 * @since 1.0.0
 * 
 * @version 1.0.0
 * 
 */
@Order(2)
public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    /* 应用上下文，除web部分 */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        // 加载配置文件类，需要使用@Configuration注解进行标注
        return new Class[] { AppConfig.class };
    }

    /* web上下文 */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return new Class[] { MvcConfig.class };
    }

    /* DispatcherServlet的映射路径 */
    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }

    /* 注册过滤器，映射路径与DispatcherServlet一致，路径不一致的过滤器需要注册到另外的WebApplicationInitializer中 */
    @Override
    protected Filter[] getServletFilters() {
        CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
        characterEncodingFilter.setEncoding("UTF-8");
        characterEncodingFilter.setForceEncoding(true);

        return new Filter[] { characterEncodingFilter };
    }

    @Override
    protected void customizeRegistration(Dynamic registration) {
        // http://jinnianshilongnian.iteye.com/blog/1684403
        registration.setInitParameter("dispatchOptionsRequest", "true");
    }

}
